<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="author" content="PIXINVENT">
    <title>999后台管理系统</title>
    <script src="app-assets/js/Dream.js"></script>
    <script src="app-assets/js/Http.js"></script>
    <link rel="stylesheet" type="text/css" href="app-assets/css/vendors.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/vertical-menu.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css">
</head>
<style>
    #shoppingNumber {
        /*设置成盒子模型*/
        display: inline-block;
        background-color: #333333;
        border-radius: 50%;
        /* 设置宽高 */
        width: 18px;
        height: 18px;
        /* 设置文字居中 */
        text-align: center;
        /* 设置文字居中 */
        line-height: 18px;
        /* 设置文字大小 */
        font-size: 8px;
        color: white;
    }
</style>
<body>
<div class="content-wrapper">
    <div class="content-header ">
        <div class="content-header-left mb-2">
            <h3 class="content-header-title mb-0">订购列表</h3>
        </div>
    </div>
    <div class="card">
        <div class="card-content">
            <div class="card-body">
                <div class="searchbox">
                    <form class="form-inline">
                        <div class="form-group">
                            <input type="text" class="form-control" id="productId" placeholder="请填写商品ID">
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" id="productName" placeholder="请填写商品名称">
                        </div>

                        <div class="form-group">
                            <button type="button" class="btn btn-primary" onclick="selects()">查询</button>
                        </div>

                    </form>
                </div>

                <div class="tablebox1">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>商品图片</th>
                            <th>商品名称</th>
                            <th>商品类别</th>
                            <th>商品品牌</th>
                            <th>商品售价</th>
                            <th>商品描述</th>
                            <th>下单数量</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="showT">

                        </tbody>
                    </table>

                    <div class="page clearfix">
                        <div class="pull-left">共 <span id="total"></span> 条记录 第 <span id="pageNum"></span> / <span
                                id="pages"></span> 页
                        </div>
                        <div class="pull-right">

                            <nav aria-label="..." class="pull-left">
                                <ul class="pagination" id="pageTo">

                                </ul>
                            </nav>
                            <div class="pull-left p-l-20"><a class="" href="#" onclick="pageTo()">跳至</a><input
                                    type="text" value="" class="form-control" id="pageNumber">页
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>
    </div>
    <!--购物车-->
    <div class="cart-box">
        <div class="cart-title">
            <div class="pull-left">
                <span style="  font-size: 18px;" onclick="showS()"><a href="#">订购车</a></span>&nbsp;<span
                    id="shoppingNumber">0</span>
            </div>
            <div class="pull-right">
                合计：<span class="total-price red" id="totalAmount">0</span>&nbsp;&nbsp;&nbsp;
                <a href="#" class="btn btn-primary" onclick="getTO()">结算</a>
                <a href="#" class="btn btn-danger" onclick="getClear()">清空</a>
            </div>
        </div>
        <div class="cart-list">
            <table id="cartTab" class="table">
                <thead>
                <tr>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>商品数量</th>
                    <th>操作</th>
                    <th>小计</th>
                </tr>
                </thead>
                <tbody id="cartT">
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="app-assets/js/vendors.min.js" type="text/javascript"></script>
<script src="app-assets/js/app-menu.js" type="text/javascript"></script>
<script src="app-assets/js/app.js" type="text/javascript"></script>
<script src="app-assets/js/echarts.min.js" type="text/javascript"></script>

</body>
</html>
<script>
    $(document).ready(function () {
        $('#cartTab').css('display', 'none')
        selectAll($('#productId').val(), $('#productName').val(), 1)
        if(sessionStorage.getItem(  "loginName") == undefined){
            Dreamer.warning("请先登录！",1000,function (){
                window.location.href = "../index.html"
            })
        }
    });

    function selectAll(productId, productName, pageNum) {
        $.ajax({
            'url': HTTP.getUserInfo + '/products',
            'type': 'get',
            'dataType': 'json',
            'data': {productId, productName, pageNum},
            'success': selectAllSuccess
        })
    }

    function selects() {
        selectAll($('#productId').val(), $('#productName').val(), 1)
    }

    function selectAllSuccess(data) {
        $('#showT tr').remove()

        data.data.list.forEach(dd => {
            $('#showT').append(`<tr>
                            <td><img src="` + HTTP.getUserInfo + `/` + dd.imageUrl + `" width="60"></td>
                            <td>` + dd.productName + `</td>
                            <td>` + dd.categoryName + `</td>
                            <td>` + dd.brand + `</td>
                            <td>￥` + dd.price + `</td>
                            <td>` + dd.description + `</td>
                            <td><input  class="form-control w-50"    type="number"></td>
                            <td>
                                <a href="#" onclick="addCart(this,` + dd.productId + `,'` + dd.productName + `',` + dd.price + `)" class="btn btn-primary btn-td">添加</a>
                                <a href="#" class="btn btn-danger btn-td" onclick="deleteCart(` + dd.productId + `)">删除</a>
                            </td>
                        </tr>`)
        })
        $('#total').html(data.data.total)
        $('#pageNum').html(data.data.pageNum)
        $('#pages').html(data.data.pages)
        $('#pageSize').html(data.data.pageSize)
        let upP = ''
        if (data.data.pageNum == 1) {
            upP = 'disabled'
        }
        let neP = ''
        if (data.data.pageNum == data.data.pages) {
            neP = 'disabled'
        }
        let pageTo = ''
        pageTo += `<li class="` + upP + `" onclick="upPage()"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>`
        for (let i = 1; i <= data.data.pages; i++) {
            if (i == data.data.pageNum) {
                pageTo += `<li class="active"><a href="#">${i} <span class="sr-only">(current)</span></a></li>`
            } else {
                pageTo += `<li><a href="#">${i}</a></li>`
            }
        }
        pageTo += `<li class="` + neP + `" onclick="nePage()"><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>`
        $('#pageTo').html(pageTo)

        $('#pageTo a').click(function () {
            let pageNum = $(this).html()
            selectAll($('#productId').val(), $('#productName').val(), pageNum)
        })
    }

    function upPage() {
        let pageNum = $('#pageNum').html()
        pageNum--
        selectAll($('#productId').val(), $('#productName').val(), pageNum)
    }

    function nePage() {
        let pageNum = $('#pageNum').html()
        pageNum++
        selectAll($('#productId').val(), $('#productName').val(), pageNum)
    }

    function pageTo() {
        let pageNum = $('#pageNumber').val()
        selectAll($('#productId').val(), $('#productName').val(), pageNum)
    }


    function addCart(e, productId, productName, money) {
        let num = $(e).parent().parent().find('input').val()
        if (num <= 0) {
            Dreamer.error('请填写正确的数量', 1000);
            return
        }
        // 如果有重复的记录原先的数量和后面相加
        $('#cartT tr').each(function () {
            if ($(this).find('td').eq(0).html() == productName) {
                let oldNum = $(this).find('td').eq(2).find('input').val()
                num = parseInt(num) + parseInt(oldNum)
                $(this).find('td').eq(2).find('input').val(num)
                $(this).find('td').eq(4).html(money * num)
                $(this).remove()
            }
        })
        // 如果没有重复的记录就添加
        $('#cartT').append(`<tr>
         <td id="ID-` + productId + `">` + productName + `</td>
          <td>` + money + `</td>
          <td><input type="number" class="form-control w-25" oninput="updateCart(this)" value="` + num + `"></td>
          <td>
              <a href="#" class="btn btn-danger btn-td" onclick="deleteCart(` + productId + `)">删除</a>
          </td>
          <td>` + money * num + `</td>
      </tr>`)
        // 清空number
        $(e).parent().parent().find('input').val('')
        //计算总计
        let totalAmount = 0
        $('#cartT tr').each(function () {
            totalAmount += parseInt($(this).find('td').eq(4).html())
        })
        $('#totalAmount').html(totalAmount)
        // 计算购物车数量
        let shoppingNumber = $('#shoppingNumber').html()
        shoppingNumber = parseInt(shoppingNumber) + 1
        $('#shoppingNumber').html(shoppingNumber)
        // 如果大于1，将购物车数量背景色设置成红色
        if (shoppingNumber > 0) {
            $('#shoppingNumber').css('background-color', 'red')
        }
    }

    function updateCart(e) {
        let num = $(e).val()
        let money = $(e).parent().parent().find('td').eq(1).html()
        if (num <= 0) {
            Dreamer.error('最少要有一个商品', 1000);
            $(e).val(1)
        } else {
            $(e).parent().parent().find('td').eq(4).html(money * num)
        }
        let totalAmount = 0
        $('#cartT tr').each(function () {
            totalAmount += parseInt($(this).find('td').eq(4).html())
        })
        $('#totalAmount').html(totalAmount)
    }

    function deleteCart(productId) {
        // 删除 #cartT的数据
        $('#cartT tr').each(function () {
            if ($(this).find('td').eq(0).attr('id') == 'ID-' + productId) {
                $(this).remove()
            }
        })
        let totalAmount = 0
        $('#cartT tr').each(function () {
            totalAmount += parseInt($(this).find('td').eq(4).html())
        })
        $('#totalAmount').html(totalAmount)
        // 计算购物车数量
        let shoppingNumber = $('#shoppingNumber').html()
        shoppingNumber = parseInt(shoppingNumber) - 1
        $('#shoppingNumber').html(shoppingNumber)
        // 如果小于等于0，将购物车数量背景色设置成灰色
        if (shoppingNumber <= 0) {
            $('#shoppingNumber').css('background-color', '#333333')
        }
    }

    // 清空
    function getClear() {
        $('#cartT tr').remove()
        $('#totalAmount').html(0)
        $('#shoppingNumber').html(0)
        $('#shoppingNumber').css('background-color', '#333333')
    }

    function showS() {
        // 展示关闭购物车
        if ($('#cartTab').css('display') == 'none') {
            $('#cartTab').css('display', '')
        } else {
            $('#cartTab').css('display', 'none')
        }
    }

    function getTO() {
        let purchaseOrderDetailsDTOList = []
        $('#cartT tr').each(function () {
            let productId = $(this).find('td').eq(0).attr('id').split('-')[1]
            let unitPrice = $(this).find('td').eq(1).html()
            let quantity = $(this).find('td').eq(2).find('input').val()
            let createdBy = sessionStorage.getItem('loginName')

            // 以json格式存放一个变量
            let json = {
                'productId': productId,
                'unitPrice': unitPrice,
                'quantity': quantity,
                'createdBy': createdBy
            }
            purchaseOrderDetailsDTOList.push(json)

        })
        $.ajax({
            'url': HTTP.getUserInfo + '/purchaseOrderDetails',
            'type': 'post',
            'dataType': 'json',
            'contentType': 'application/json',
            'data': JSON.stringify({
                purchaseOrderDetailsDTOList
            }),
            'success': getTOSuccess
        })
    }

    function getTOSuccess(data) {
        if (data.code == 200) {
            Dreamer.success('订购成功', 1000)
            getClear()
        } else {
            Dreamer.error(data.message, 1000)
        }
    }

</script>